<template>
  <div class="yemian">
    <div class="dingbu">
      <div class="biaoti">
        <img src="../assets/image/纸飞机.png" class="tubiao">
        <span class="wz">NBM在线考试系统</span>
      </div>
      <NavBar />
      <div class="touxiang">
        <img src="../assets/image/头型.png" style="height: 50px; width: 50px;">
        <UserInfo />
      </div>
    </div>
    <div class="teacher-info-container">
      <el-card class="box-card">
        <template #header>
          <div class="card-header">
            <span>教师信息管理</span>
          </div>
        </template>

        <div style="display: flex;">
          <img src="../assets/image/3.png" style="width: 180px; height: 180px;">
          <el-form 
            :model="form" 
            :rules="rules" 
            ref="teacherForm"
            label-width="100px"
            label-position="left"
          >
            <el-form-item label="用户名：" prop="username">
              <el-input v-model="form.username" disabled />
            </el-form-item>

            <el-form-item label="角色：" prop="user_type">
              <el-input :value="form.user_type === 1 ? '教师' : '学生'" disabled />
            </el-form-item>

            <el-form-item label="手机号：" prop="phone">
              <el-input v-model="form.phone" placeholder="请输入手机号" clearable />
            </el-form-item>

            <el-form-item label="状态：" prop="status">
              <el-input :value="form.status === 1 ? '已激活' : '未激活'" disabled />
            </el-form-item>

            <el-form-item>
              <el-button 
                type="primary" 
                @click="submitForm"
                :loading="loading"
              >
                保存
              </el-button>
            </el-form-item>
          </el-form>
        </div>
      </el-card>
    </div>
  </div>
</template>

<script setup>
import NavBar from '../components/NavBar.vue';
import UserInfo from '../components/UserInfo.vue';
import { ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import axios from 'axios'
import { useRouter } from 'vue-router'
const router = useRouter()
// import { getToken } from '@/utils/auth'
const getToken = () => localStorage.getItem('token')

// 表单数据
const form = ref({
  id: '',
  username: '',
  phone: '',
  user_type: 1, // 1表示教师
  status: 0,
  password: ''
})

// 验证规则
const rules = {
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { 
      pattern: /^1[3-9]\d{9}$/,
      message: '请输入正确的手机号格式',
      trigger: ['blur', 'change']
    }
  ]
}

const loading = ref(false)
const teacherForm = ref(null)

// 获取教师信息
const fetchTeacherData = async () => {
  try {
    const response = await axios.get('http://192.168.43.63:8080/api/user/current', {
      headers: {
        'Authorization': 'Bearer '+localStorage.getItem('token')
      }
    })
    
    form.value = {
      id: response.data.id,
      username: response.data.username,
      phone: response.data.phone,
      user_type: response.data.user_type,
      status: response.data.status
    }
  } catch (error) {
    if (error.response?.status === 403) {
    router.push('/login')
  }
    ElMessage.error('获取教师信息失败')
    console.error('Error fetching teacher data:', error)
  }
}

// 提交表单
const submitForm = async () => {
  try {
    loading.value = true
    await teacherForm.value.validate()
    
    const payload = {
      phone: form.value.phone,
      // 可以添加其他可修改的字段
    }
    
    await axios.put(`http://192.168.43.173:8080/api/users/${form.value.id}`, payload, {
      headers: {
        'Authorization': `Bearer ${getToken()}`,
        'Content-Type': 'application/json'
      }
    })
    
    ElMessage.success('保存成功')
  } catch (error) {
    if (error.response) {
      ElMessage.error(`保存失败: ${error.response.data.message || '服务器错误'}`)
    } else if (!error.message.includes('validate')) {
      ElMessage.error('网络错误，请稍后重试')
    }
  } finally {
    loading.value = false
  }
}

// 初始化时获取数据
onMounted(() => {
  fetchTeacherData()
})
</script>

<style scoped>
.yemian {
  width: 100%;
  min-height: 100vh;
  padding: 0 20px;
  box-sizing: border-box;
}

.dingbu {
  width: 100%;
  height: 80px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  border-bottom: 1px solid #e0e0e0;

  box-sizing: border-box;
}

.biaoti {
  display: flex;
  align-items: center;
  gap: 10px;
}

.tubiao {
  height: 40px;
  width: 40px;
}

.wz {
  color: #333;
  font-size: 24px;
  font-weight: bold;
}

.touxiang {
  display: flex;
  align-items: center;
  gap: 10px;
}




.touxiang {
  width: 200px;
  display: flex;
  justify-content: flex-end;
  align-items: center;
}
.teacher-info-container {
  padding: 20px;
  max-width: 800px;
  margin: 0 auto;
}

.card-header {
  font-size: 18px;
  font-weight: bold;
}

.el-form {
  padding: 0 20px;
}

.el-input {
  width: 300px;
}
</style>